﻿import sys
import Hobot.GPIO as GPIO
import time

# 初始化全局变量
Echo_In = 0
Trig_Out = 0

def setup():
    global Echo_In
    global Trig_Out

    Echo_In = int(sys.argv[1])  # 从命令行参数中读取并转换为整数
    Trig_Out = int(sys.argv[2])  # 从命令行参数中读取并转换为整数

    print("接口设置 echo:{0}  trig:{1}".format(Echo_In,Trig_Out))

    # GPIO.cleanup()  # 清理之前的配置
    GPIO.setmode(GPIO.BOARD)  # 设置GPIO模式

    GPIO.setup(Echo_In, GPIO.IN, initial=GPIO.HIGH)
    GPIO.setup(Trig_Out, GPIO.OUT, initial=GPIO.LOW)
   
    

def distanceStart():

    GPIO.output(Trig_Out, GPIO.LOW)
    time.sleep(0.5)
    GPIO.output(Trig_Out, GPIO.HIGH)
    time.sleep(0.00001)
    GPIO.output(Trig_Out, GPIO.LOW)




  
    # # 等待结束记录时间
    # while not GPIO.input(Echo_In):
    # 
    #     pass
    # 
    # 
    # 
    # 
    # pulse_start = time.time()
    # 
    # # 等待高电平结束
    # while GPIO.input(Echo_In):
    #     pass
    # pulse_end = time.time()

    # Wait for the ECHO pin to go HIGH and then LOW
    while GPIO.input(Echo_In) == GPIO.LOW:
        pulse_start = time.time()
    while GPIO.input(Echo_In) == GPIO.HIGH:
        pulse_end = time.time()


    # 计算距离
    duration = pulse_end - pulse_start
    distance = duration * 17150  # 厘米单位 340/2 * 100
    # 取整
    distance = round(distance)


    return distance

def loop():
    while True:
        distance = distanceStart()

        # 输出监听举例
        print(distance)

        time.sleep(1)  # 测距间隔

def destroy():
    GPIO.cleanup()

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print("Usage: python script.py <Echo_In> <Trig_Out>")
        sys.exit(1)

    setup()
    try:
        loop()
    except KeyboardInterrupt:
        destroy()
    finally:
        destroy()
